<template>
  <div ref="boxwrap" class="mt-50 Roles-setting">
    <el-row :gutter="20">
      <el-col v-for="(item, index) in list" :key="index" :span="6">
        <el-card class="box-card" :class="{'activeBgc': activeRole === item.roleId}">
          <div class="role-item">
            <span class="icons"><i class="el-icon-user-solid" /></span>
            <div>
              <h4>{{ item.roleName }}</h4>
              <p>该角色拥有【{{ item.desc }}】权限</p>
              <p>该角色目前已配置 <em style="color: #F56C6C">{{ roleNum[item.roleId] }}</em> 个用户</p>
            </div>
            <el-button-group class="operate-btns">
              <!-- <el-button type="primary" size="small " plain>查看权限</el-button> -->
              <el-button type="primary" size="small " plain @click="checkRole(item.roleId, item.roleName)">查看用户</el-button>
              <!-- <el-button type="primary" size="small " plain>关联用户</el-button> -->
            </el-button-group>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="table-wrap">
      <el-col :span="12">
        <h4>{{ activeRoleName }}用户</h4>
        <el-table
          key="1"
          :data="tableList"
          border
          fit
          style="width: 100%;"
          size="small"
          :height="tableHeight"
          :max-height="tableHeight"
        >
          <el-table-column label="序号" align="center" type="index" width="60" :index="indexMethod" />
          <el-table-column v-for="(item, index) in tableCol" :key="index" :label="item.label" align="center" :width="item.width || ''">
            <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="130">
            <template slot-scope="{row}">
              <el-button-group>
                <el-button type="primary" size="small " icon="el-icon-edit" @click="setRole(row)">
                  分配权限
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <h4>未配置角色用户</h4>
        <el-table
          key="2"
          :data="unSetRoleUserList"
          border
          fit
          style="width: 100%;"
          size="small"
          :height="tableHeight"
          :max-height="tableHeight"
        >
          <el-table-column label="序号" align="center" type="index" width="60" :index="indexMethod" />
          <el-table-column v-for="(item, index) in tableCol" :key="index" :label="item.label" align="center" :width="item.width || ''">
            <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="130">
            <template slot-scope="{row}">
              <el-button-group>
                <el-button type="primary" size="small " icon="el-icon-edit" @click="setRole(row)">
                  分配权限
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-dialog title="权限分配" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" class="dialog-form">
        <el-form-item label="用户名">
          <el-input v-model.trim="temp.userName" placeholder="请输入" readonly />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model.trim="temp.nickName" placeholder="请输入" readonly />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="temp.roleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="制程权限">
          <el-select v-model="checkedRegion" multiple placeholder="请选择">
            <el-option
              v-for="item in rgionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="small" @click="updateData('dataForm')">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { defaultRoles } from '@/api/default-apis'
import { getUserList, updateRoleAuth } from '@/api/user'
import { getProcess } from '@/api/conf'

export default {
  name: 'Roles',
  data() {
    return {
      list: [],
      roleList: [],
      roleNum: {},
      tableCol: [
        { label: '用户名', prop: 'userName' },
        { label: '昵称', prop: 'nickName' },
        { label: '角色', prop: 'roleName' },
        { label: '状态', prop: 'stateStr', width: 80 },
        { label: '制程权限', prop: 'regionStr' }
      ],
      tableHeight: 'auto',
      tableList: [],
      unSetRoleUserList: [], // 分配角色的全部的userlist
      activeRole: null,
      activeRoleName: '',
      allUserList: [],
      userState: {
        0: '离职',
        1: '在职'
      },
      rgionList: [],
      regionStrArr: [],
      dialogFormVisible: false,
      checkedRegion: [],
      temp: {},
      logedUser: {},
      regionNameObj: {}
    }
  },
  mounted() {
    this.getTableHeight()
  },
  created() {
    this.getProcessList()
    this.logedUser = JSON.parse(this.$Cookies.get('logedUser'))
  },
  methods: {
    getTableHeight() {
      const that = this
      const dom = this.$refs.boxwrap
      this.$erd.listenTo(dom, function(element) {
        that.tableHeight = dom.clientHeight - 160 - 100
      })
    },
    getProcessList() {
      getProcess().then(res => {
        this.rgionList = res.data
        res.data.forEach(item => {
          this.regionNameObj[item.id] = item.name
        })
        this.getAllRoles()
      })
    },
    getAllRoles() {
      defaultRoles().then(res => {
        res.roleList.forEach(val => {
          val.disabled = this.logedUser.roleId > val.roleId
        })
        this.roleList = [].concat(res.roleList)
        this.roleList.forEach(item => {
          this.roleNum[item.roleId] = 0
        })
      })
      getUserList().then(res => {
        res.data.forEach(item => {
          this.roleNum[item.roleId]++
          item.stateStr = this.userState[item.state]
        })
        this.allUserList = [].concat(res.data)
        this.list = [].concat(this.roleList)
        this.getTableData()
        if (this.activeRoleName !== '') {
          this.getTableData(this.activeRole, this.activeRoleName)
        }
      })
    },
    // 不传roleId，查未分配的
    getTableData(roleId, roleName) {
      if (roleId === undefined) {
      // 获取未分配角色的全部的userlist
        this.unSetRoleUserList = this.allUserList.filter(item => {
          return item.roleId === undefined || item.roleId === null
        })
      } else { // 某角色的user
        this.tableList = this.allUserList.filter(item => {
          item.roleName = roleName
          if (item.regionId) {
            item.regionStr = item.regionId.split(',').map(val => { return this.regionNameObj[parseInt(val)] }).join(',')
          } else {
            item.regionStr = ''
          }
          return item.roleId === roleId
        })
      }
    },
    indexMethod(index) {
      return index + 1
    },
    checkRole(roleId, roleName) {
      this.activeRole = roleId
      this.activeRoleName = roleName
      this.getTableData(roleId, roleName)
    },
    setRole(row) {
      this.temp = Object.assign({}, row)
      if (this.temp.roleId === null || this.logedUser.roleId < this.temp.roleId || (this.logedUser.roleId === this.temp.roleId && this.logedUser.userName === this.temp.userName)) {
        if (this.temp.regionId !== '') {
          this.checkedRegion = this.temp.regionId.split(',').map(v => { return parseInt(v) })
        }
        this.dialogFormVisible = true
      } else {
        this.$message({
          message: '权限不够，请联系上级管理员',
          type: 'warning'
        })
      }
    },
    updateData(formname) {
      this.$refs[formname].validate((valid) => {
        const paramObj = {
          regionId: this.checkedRegion.join(','),
          roleId: this.temp.roleId,
          userId: this.temp.userId
        }
        paramObj.regionId = this.checkedRegion.join(',')
        updateRoleAuth(paramObj).then(res => {
          let msgType = 'error'
          if (res.code === '000000') {
            msgType = 'success'
          }
          this.$message({
            message: msgType,
            type: msgType,
            duration: 2000
          })
          this.cancel()
          // this.getTableData()
          this.roleNum = {}
          this.getAllRoles()
        })
      })
    },
    cancel() {
      this.dialogFormVisible = false
      this.temp = {}
    }
  }
}
</script>

<style lang="scss" scoped>
.Roles-setting {
  height: calc(100% - 50px);
}
.role-item{
  position: relative;
  text-align: center;

  .status-btn{
    position: absolute;
    top: 0;
    right: 0;
  }

  .icons{
    display: block;
    width: 40px;
    height: 40px;
    border: 1px solid #fff;
    border-radius: 50%;
    margin: 0 auto;
    font-size: 32px;
    text-align: center;
    line-height: 40px;

  }

  h4, p{
    margin: 10px 0;
  }
  p{
    font-size: 14px;
  }

.operate-btns{
    .el-button{
      color: #f1f1f1;
      background: rgba(63, 81, 181, 0.3);
      border-color: #5967a4;
    }
    .el-button--primary.is-plain:hover, .el-button--primary.is-plain:focus {
        background: #0095e3;
        border-color: #0095e3;
        color: #FFFFFF;
    }
}

}

.activeBgc {
  background: rgba(63, 81, 181, 0.8);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.6);
}

.table-wrap{
  height: calc(100% - 190px);
  .el-col {
    height: 100%;
  }
}
</style>
